package csu.web.mypetstore.controller;

import csu.web.mypetstore.pojo.Category;
import csu.web.mypetstore.pojo.Product;
import csu.web.mypetstore.service.CategoryService;
import csu.web.mypetstore.service.ImageService;
import csu.web.mypetstore.service.ItemService;
import csu.web.mypetstore.service.ProductService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@Controller
@RequestMapping("products")
public class ProductController {
    @Autowired
    private ProductService productService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private ImageService imageService;
    @Autowired
    private ItemService itemService;





    @PostMapping("add")
    @Transactional
    public String addProduct(
            @RequestParam("productid") String productId,
            @RequestParam("category") String category,
            @RequestParam("name") String name,
            @RequestParam("description") String descn,
            @RequestParam("image") MultipartFile file
    ) {


        Product product = new Product();
        product.setProductid(productId);
        product.setCategory(category);
        product.setName(name);
        String image=imageService.saveImage(file, category);
        product.setDescn(image+descn);

        productService.addNewProduct(product);


        return "redirect:/cmsCategoryForm?categoryId="+category;
    }
    // 删除产品
    @GetMapping("delete")
    @Transactional
    public String deleteProduct(
            @RequestParam("productId") String productId,
            @RequestParam("categoryId") String categoryId
    ){
        productService.deleteProduct(productId);
        itemService.deleteItemInProduct(productId);
        return "redirect:/cmsCategoryForm?categoryId="+categoryId;
    }

    @PostMapping("update")
    @Transactional
    public String updateProduct(
            @RequestParam("productid") String productId,
            @RequestParam("category") String category,
            @RequestParam("name") String name,
            @RequestParam("description") String descn,
            @RequestParam("image") MultipartFile file
    ){

        productService.updateProductCategory(category, productId);
        productService.updateProductName(name, productId);
        if(!file.isEmpty()) {
            productService.updateProductDescn(imageService.saveImage(file, category) + descn, productId);
        }else {
            Product product = productService.getProduct(productId);
            productService.updateProductDescn(product.getImage() + descn, productId);
        }
        return "redirect:/cmsCategoryForm?categoryId="+category;
    }

}